package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.R;
import com.itheima.dao.OrdersDao;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.*;
import com.itheima.exception.CustomException;
import com.itheima.service.*;
import com.itheima.utils.BaseContext;
import com.itheima.utils.BeanCopyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @date 2023/4/17
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {
    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 下单
     *
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //0.开启事务（涉及到两张表的新增操作）
        //0.查询当前登录的用户id
        Long userId = BaseContext.getValue();
        User user = userService.getById(userId);
        if (user == null) {
            throw new CustomException("该用户不存在！");
        }

        //1.保存订单数据到订单明细表order_detail
        //1.1 构造订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();

        //通过IdWorker自动生成id，底层策略雪花算法
        long orderId = IdWorker.getId();

        //1.2 查询购物车，遍历购物车数据，将shoppingCart拷贝到orderDetail对象中，忽略id属性
        LambdaQueryWrapper<ShoppingCart> cartWrapper = new LambdaQueryWrapper<>();
        cartWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> cartList = shoppingCartService.list(cartWrapper);
        if (cartList == null) {
            throw new CustomException("请先添加商品到购物车！");
        }
        //定义一个总金额
        BigDecimal sumAmount = new BigDecimal(0);
        for (ShoppingCart shoppingCart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            //1.3 将用户id封装到orderDetail中
            BeanUtils.copyProperties(shoppingCart, orderDetail, "id");
            //1.4 绑定订单id(可以通过一个id生成工具类生成)
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);
            //1.5 计算总金额
            sumAmount = sumAmount.add(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())));
        }
        orderDetailService.saveBatch(orderDetailList);

        //2.保存订单数据到订单表orders
        //2.1 设置id字段值（根据上面生成的id来设置）
        orders.setId(orderId);

        //2.2 补齐字段
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(2);  //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setUserName(user.getName());     //用户姓名
        //查询地址簿，根据addressBookId
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //设置订单总金额
        orders.setAmount(sumAmount);

        //2.3 调用save保存方法
        this.save(orders);

        //3.下单成功后，需要清理购物车
        shoppingCartService.remove(cartWrapper);
    }

    @Override
    public R getuserPage(Integer page, Integer pageSize, HttpSession session) {
        //获取用户id
        Long userId = (Long) session.getAttribute("user");
        //分页配置
        Page<Orders> pageInfo = new Page<>();
        //开启查询条件
        LambdaQueryWrapper<Orders> orderQuery = new LambdaQueryWrapper<>();
        //精确查询用户id  结账时间进行排序
        orderQuery.eq(Orders::getUserId, userId)
                .orderByDesc(Orders::getCheckoutTime);
        this.page(pageInfo, orderQuery);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //将pageinfo拷贝到pagedto
        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");
        //将order的信息移到orderdto，在补全订单详细
        List<Orders> records = pageInfo.getRecords();
        //使用工具类 将orders集合复制到ordersDto
        List<OrdersDto> ordersDtos = BeanCopyUtils.beanListCopy(records, OrdersDto.class);
        ordersDtos = ordersDtos.stream().map((item) -> {
            //根据订单id查询订单明细
            LambdaQueryWrapper<OrderDetail> orderQueryWrapper = new LambdaQueryWrapper<>();
            //TODO 分页查询订单详细
            orderQueryWrapper.eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(orderQueryWrapper);
            //设置订单详情
            item.setOrderDetails(orderDetails);
            item.setUserName(item.getConsignee());
            return item;
        }).collect(Collectors.toList());
        //封装信息到page
        ordersDtoPage.setRecords(ordersDtos);
        return R.success(ordersDtoPage);
    }
    public R<String> again(OrdersDto ordersDto) {
        //根据订单id查询
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId, ordersDto.getId());
        //根據ordersDto的id獲取訂單詳情的集合
        List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);
        List<ShoppingCart> cartArrayList = orderDetailList.stream().map((orderDetail) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getValue());
            return shoppingCart;
        }).collect(Collectors.toList());
        //清空购物车（需要則取消注釋，否則不用）
        //shoppingCartService.remove();
        //
        shoppingCartService.saveOrUpdateBatch(cartArrayList);
        return R.success("再來一單");

    }



}
